package cn.shenlong.portal.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.shenlong.common.Constants;
import cn.shenlong.domain.TreeNode;
import cn.shenlong.portal.domain.Application;
import cn.shenlong.portal.domain.Channel;
import cn.shenlong.portal.service.ApplicationService;
import cn.shenlong.portal.service.ChannelService;

@Controller
@RequestMapping("/channel/admin")
public class ChannelAController {

	@Autowired
	private ChannelService channelService;

	@Autowired
	private ApplicationService applicationService;

	/**
	 * 跳转栏目管理界面
	 * 
	 * @return
	 */
	@RequestMapping("/index")
	public String index() {
		return "/server/channel/index";
	}

	/**
	 * 跳转栏目树页面
	 * 
	 * @return
	 */
	@RequestMapping("/lefttree")
	public String lefttree() {
		return "/server/channel/lefttree";
	}

	/**
	 * 跳转栏目编辑页面
	 * 
	 * @param channelId
	 *            当前栏目ID
	 * @param isLastNode
	 *            标记是否是叶子节点，提供删除的判断操作 1:是
	 * @param model
	 * @return
	 */
	@RequestMapping("/right")
	public String right(Long channelId, Long isLastNode, ModelMap model) {
		if (channelId != null) {
			Channel channel = channelService.findByPK(channelId);
			if (channel != null) {
				if (channel.getParentId() != null && channel.getParentId() > 0) {
					Channel pChannel = channelService.findByPK(channel
							.getParentId());
					model.addAttribute("pChannel", pChannel);
				}
				// 判断该栏目是否为版位栏目
				List<Application> applicationList = applicationService
						.getNaOrLaByChannelId(2l, channelId);
				Application application = null;
				if (applicationList != null && applicationList.size() > 0) {
					application = applicationList.get(0);
				} else {
					application = new Application();
					application.setPriority(0l);
				}
				model.addAttribute("application", application);
				model.addAttribute("isLastNode", isLastNode);
				model.addAttribute("channel", channel);
				return "/server/channel/right";
			} else {
				model.addAttribute("errorMsg", "查询不到相关栏目!");
			}
		} else {
			model.addAttribute("errorMsg", "栏目ID丢失!");
		}
		return "/common/error";
	}

	/**
	 * 获取栏目树
	 * 
	 * @return
	 */
	@RequestMapping("/getTree")
	@ResponseBody
	public List<TreeNode<Long>> getTree() {
		List<TreeNode<Long>> treeList = new ArrayList<TreeNode<Long>>();// 用于存储栏目树数据
		List<Channel> list = channelService.getList();
		// 新增本站栏目目录对象
		TreeNode<Long> treeFirst = new TreeNode<Long>();
		treeFirst.setId(0l);
		treeFirst.setpId(-3l);
		treeFirst.setName("本站栏目");
		treeFirst.setOpen(true);
		treeList.add(treeFirst);
		if (list != null && list.size() > 0) {
			for (Channel c : list) {
				TreeNode<Long> tree = new TreeNode<Long>();
				tree.setId(c.getChannelId());
				tree.setpId(c.getParentId());
				tree.setName(c.getTitle());
				tree.addAttributes("channelType", c.getChannelType());// 栏目类型
				tree.setOpen(false);
				treeList.add(tree);
			}
		}
		return treeList;
	}

	/**
	 * 跳转新增栏目界面
	 * 
	 * @param pChannelId
	 *            父栏目ID
	 * @param addType
	 *            当站点下没有栏目时，引导添加栏目 标记状态。默认为1
	 * @param model
	 * @return
	 */
	@RequestMapping("/add")
	public String add(Long pChannelId, Long addType, ModelMap model) {
		if (addType != null && addType == 1) {
			Channel pChannel = new Channel();
			pChannel.setTitle("顶级栏目");
			pChannel.setChannelId(0l);
			model.addAttribute("pChannel", pChannel);
			return "/server/channel/add";
		} else {
			if (pChannelId != null && pChannelId > 0) {
				Channel pChannel = channelService.findByPK(pChannelId);
				model.addAttribute("pChannel", pChannel);
				return "/server/channel/add";
			} else {
				model.addAttribute("errorMsg", "父栏目ID丢失!");
				return "/common/error";
			}
		}
	}

	/**
	 * 保存栏目
	 * 
	 * @param channel
	 * @param model
	 * @param priority
	 *            版位栏目位置
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public Map<String, String> save(Channel channel, Long priority,
			ModelMap model) {
		Map<String, String> resultMap = new HashMap<String, String>();
		// 判断版位是否被占用
		if (priority != null && priority > 0) {
			List<Application> applicationList = applicationService.getNaOrLa(
					2l, priority);// type 1：导航条 2：版位
			if (applicationList != null && applicationList.size() > 0) {
				resultMap.put("resultText", "error");
				resultMap.put("message", "版位 " + priority + " 已经存在栏目，请先调整!");
				return resultMap;
			} else {
				if (channel.getChannelType() == 1) {
					channel.setTxt("");// 重置栏目内容 (channelType==1 为新闻类型；2 为单页类型)
				}
				channelService.saveEntity(channel);
				Application application = new Application();
				application.setApplicationType(2l);
				application.setChannelId(channel.getChannelId());
				application.setChannelName(channel.getTitle());
				application.setPriority(priority);
				applicationService.saveEntity(application);
				resultMap.put("resultText", "success");
				resultMap.put("message", "保存栏目信息成功!");
				return resultMap;
			}
		}
		if (channel.getChannelType() == 1) {
			channel.setTxt("");// 重置栏目内容 (channelType==1 为新闻类型；2 为单页类型)
		}
		channelService.saveEntity(channel);
		resultMap.put("resultText", "success");
		resultMap.put("message", "保存栏目信息成功!");
		return resultMap;
	}

	/**
	 * 更新栏目
	 * 
	 * @param channel
	 * @param originalPosition
	 *            原始版位
	 * @param priority
	 *            版位栏目位置
	 * @param model
	 * @return
	 */
	@RequestMapping("/update")
	@ResponseBody
	public Map<String, String> update(Channel channel, Long originalPosition,
			Long priority, ModelMap model) {
		Map<String, String> resultMap = new HashMap<String, String>();
		// 判断版位是否被占用
		if (originalPosition.longValue() == 0) {
			if (priority.longValue() > 0) {
				List<Application> applicationList = applicationService
						.getNaOrLa(2l, priority);// type 1：导航条 2：版位
				if (applicationList != null && applicationList.size() > 0) {
					resultMap.put("resultText", "error");
					resultMap
							.put("message", "版位 " + priority + " 已经存在栏目，请先调整!");
					return resultMap;
				}
				Application application = new Application();
				application.setApplicationType(2l);
				application.setChannelId(channel.getChannelId());
				application.setChannelName(channel.getTitle());
				application.setPriority(priority);
				applicationService.saveEntity(application);
			}
		} else {
			if (priority.longValue() > 0
					&& originalPosition.longValue() != priority.longValue()) {
				List<Application> applicationList = applicationService
						.getNaOrLa(2l, priority);// type 1：导航条 2：版位
				if (applicationList != null && applicationList.size() > 0) {
					resultMap.put("resultText", "error");
					resultMap
							.put("message", "版位 " + priority + " 已经存在栏目，请先调整!");
					return resultMap;
				}
			} else if (priority.longValue() == 0) {
				List<Application> originalList = applicationService.getNaOrLa(
						2l, originalPosition);// type 1：导航条 2：版位
				if (originalList != null && originalList.size() > 0) {
					applicationService
							.deleteByPKArray(new Long[] { originalList.get(0)
									.getApplicationId() });
				}
			}
		}
		if (channel.getChannelType() == 1) {
			channel.setTxt("");// 重置栏目内容 (channelType==1 为新闻类型；2 为单页类型)
		}
		channelService.updateEntity(channel);
		resultMap.put("resultText", "success");
		resultMap.put("message", "保存栏目信息成功!");
		return resultMap;
	}

	/**
	 * 删除栏目
	 * 
	 * @param channelId
	 *            栏目ID
	 * @param model
	 * @return
	 */
	@RequestMapping("/deleteChannel")
	@ResponseBody
	public Map<String, String> deleteChannel(Long channelId, ModelMap model) {
		Map<String, String> resultMap = new HashMap<String, String>();
		if (channelId != null && channelId > 0) {
			channelService.deleteByPKArray(new Long[] { channelId });
			resultMap.put("resultText", "success");
			resultMap.put("message", "删除栏目信息成功!");
		} else {
			resultMap.put("resultText", "error");
			resultMap.put("message", "栏目信息ID丢失!");
		}
		return resultMap;
	}

	/**
	 * 所有栏目删除结束后的引导页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/noChannel")
	public String noChannel(ModelMap model) {
		return "/server/channel/noChannel";
	}

	/**
	 * 跳转调整栏目页面
	 * 
	 * @param siteId
	 *            站点ID
	 * @param model
	 * @return
	 */
	@RequestMapping("/adjustChannel")
	public String adjustChannel(ModelMap model) {
		return "/server/channel/adjustChannel";
	}

	/**
	 * 调整栏目后，保存栏目树数据
	 * 
	 * @param channelData
	 *            前台返回回来的栏目树节点信息
	 * @return
	 */
	@RequestMapping("/saveChannel")
	@ResponseBody
	public String saveChannel(String channelData) {
		JSONArray jsonArray = JSONArray.fromObject(channelData);
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject json = jsonArray.getJSONObject(i);
			if (json.getLong("id") != 0) {
				Channel originalChannel = channelService.findByPK(json
						.getLong("id"));
				originalChannel.setParentId(json.getLong("pId"));
				channelService.updateEntity(originalChannel);
			}
		}
		return "success";
	}

	/****************************** 栏目应用(导航条、版位) *************************************/

	/**
	 * 跳转导航条管理界面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/getNavigationList")
	public String getNavigationList(ModelMap model) {
		// 导航列表
		Map<String, String> navigationMap = new LinkedHashMap<String, String>();
		StringBuffer sb = new StringBuffer();
		StringBuffer sb2 = new StringBuffer();
		for (int j = 1; j <= Integer.valueOf(Constants.NAVIGATION_NUM); j++) {
			sb.append(j);
			sb2.append(j);
			navigationMap.put(sb2.toString(), sb.toString());
			sb.delete(0, sb.length());
			sb2.delete(0, sb2.length());
		}
		List<Application> navigationList = applicationService.getNaOrLa(1l,
				null); // 1：导航条 2：版位
		model.addAttribute("navigationMap", navigationMap);
		model.addAttribute("navigationList", navigationList);
		model.addAttribute("total", Integer.valueOf(Constants.NAVIGATION_NUM));
		model.addAttribute("nowNum", navigationList.size());
		model.addAttribute(
				"stillNum",
				Integer.valueOf(Constants.NAVIGATION_NUM)
						- navigationList.size());
		return "/server/navigation/list";
	}

	/**
	 * 跳转导航编辑页面
	 * 
	 * @param model
	 * @param request
	 * @param priority
	 *            顺序
	 * @return
	 */
	@RequestMapping("/editPriority")
	public String editPriority(ModelMap model, HttpServletRequest request,
			Long priority) {
		if (priority != null && priority > 0) {
			List<Application> applicationList = applicationService.getNaOrLa(
					1l, priority);
			if (applicationList != null && applicationList.size() > 0) {
				model.addAttribute("originalNavigation", applicationList.get(0));
			}
			model.addAttribute("originalPriority", priority);
			return "/server/navigation/editNavigation";
		} else {
			model.addAttribute("errorMsg", "导航条位置丢失!");
			return "/common/error";
		}
	}

	/**
	 * 跳转调整栏目页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/getTreeApplication")
	public String getTreeApplication(ModelMap model) {
		return "/server/navigation/treeNa";
	}

	/**
	 * 保存导航条栏目信息
	 * 
	 * @param model
	 * @param originalChannelId
	 *            原始栏目ID
	 * @param channelId
	 *            当前选择的栏目ID
	 * @param newChannelName
	 *            当前选择的栏目名称
	 * @param priority
	 *            排列顺序
	 * @return
	 */
	@RequestMapping("/savePriority")
	public String savePriority(ModelMap model, Long originalChannelId,
			String newChannelName, Long channelId, Long priority) {
		Application application = new Application();
		if (originalChannelId != null) {
			if (channelId != null && channelId > 0) {
				if (!originalChannelId.equals(channelId)) {
					// 查询当前位置的导航信息
					List<Application> applicationList = applicationService
							.getNaOrLa(1l, priority);
					if (applicationList != null && applicationList.size() > 0) {
						application = applicationList.get(0);
						application.setChannelId(channelId);
						application.setChannelName(newChannelName == null ? ""
								: newChannelName);
						applicationService.updateEntity(application);
						return "redirect:getNavigationList.htm";
					} else {
						model.addAttribute("errorMsg", "查询导航信息异常!位置为："
								+ priority);
						return "/common/error";
					}
				} else {
					return "redirect:getNavigationList.htm";
				}
			} else {
				model.addAttribute("errorMsg", "栏目ID丢失!");
				return "/common/error";
			}
		}
		Channel channel = channelService.findByPK(channelId);
		application.setChannelId(channel.getChannelId());
		application.setChannelName(channel.getTitle());
		application.setApplicationType(1l);
		application.setPriority(priority);
		applicationService.saveEntity(application);
		return "redirect:getNavigationList.htm";
	}
}